package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//合伙人系统里的公司提成记录
func NewCashRecord(cr map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	values, sql := InsertSql(TablePcCashRecord, cr)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//公司的提成
func ListCashRecord(p ListParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			cr.*,
			u.name,u.real_name
		FROM
			%v AS cr
		LEFT JOIN
			%v AS u
		ON cr.group_id = u.uid
		ORDER BY
			cr.id DESC
		LIMIT ?,?
	`, TablePcCashRecord, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var cr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&cr)
	if CheckError(err) {
		return cr, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v`, TablePcCashRecord)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return cr, 0, err
	}
	return cr, count, nil
}

func NewPbUser(user map[string]interface{}, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	values, sql := InsertSql(TablePbUser, user)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

func UpdatePbUser(user map[string]interface{}, uid int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	condition := fmt.Sprintf(`uid = %v`, uid)
	values, sql := UpdateSql(TablePbUser, user, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func PbUserInfoByName(name string, multiOrm ...orm.Ormer) (*PbUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			name = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var user PbUser
	err := o.Raw(sql, name).QueryRow(&user)
	if CheckNoExist(err) {
		return &user, nil
	}
	return &user, err
}

func PbUserInfoById(uid int64, multiOrm ...orm.Ormer) (PbUser, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			uid = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var user PbUser
	err := o.Raw(sql, uid).QueryRow(&user)
	return user, err
}

//获取合伙人的wechat
func PbUserWechatById(uid int64, multiOrm ...orm.Ormer) (string, string) {
	if uid == 0 {
		return "", ""
	}
	sql := fmt.Sprintf(`
		SELECT
			wechat_agent,wechat_business
		FROM
			%v
		WHERE
			uid = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var wAgent, wBusiness string
	o.Raw(sql, uid).QueryRow(&wAgent, &wBusiness)
	return wAgent, wBusiness
}

//pb管理用户信息
func ListPbUserInfo(p ListParams, name string, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := " 1=1 "
	if name != "" {
		where = where + fmt.Sprintf(" AND name LIKE '%v' ", "%"+name+"%")
	}
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			%v
		LIMIT ?,?
		`, TablePbUser, where)
	o := NewOrm(multiOrm, DBChessPartner)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if err != nil {
		return user, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v  WHERE %v `, TablePbUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return user, count, err
}

//根据用户名字查询用户是否已经存在
func IsPbUserExist(name string, multiOrm ...orm.Ormer) (*PbUser, bool) {
	sql := fmt.Sprintf(`
		SELECT
			uid
		FROM
			%v
		WHERE
			name = ?
		LIMIT 1
		`, TablePbUser)
	o := NewOrm(multiOrm, DBChessPartner)
	var user PbUser
	err := o.Raw(sql, name).QueryRow(&user)
	if err == orm.ErrNoRows {
		return &user, false
	}
	return &user, true
}

//判断合伙人系统里代理名下是否有代理,计算下一级的个数，包括未注册完成的，但不包括被拒绝的
func CountNextLevelAgent(agentId int64, multiOrm ...orm.Ormer) int64 {
	sql := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			pid = %v AND status != %v
	`, TablePfUser, agentId, PfVerifyNotPass)
	var count int64
	o := NewOrm(multiOrm, DBChessPartner)
	o.Raw(sql).QueryRow(&count)
	return count
}

//----------------------------合伙人系统里的代理-------------------------------------------
//所有的正式代理,包括总代，二级代理,三级代理......
func ListPartnerUser(p ListParams, op OrderParams, u PfAgentParams, multiOrm ...orm.Ormer) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := fmt.Sprintf(" u.status = %v", FirstTopUpSuccess) //正式代理
	if u.GroupId != 0 {
		where = where + fmt.Sprintf(" AND u.group_id = %v", u.GroupId)
	}
	if u.Pid != 0 {
		where = where + fmt.Sprintf(" AND u.pid = %v", u.Pid)
	}
	if u.RootId != 0 {
		where = where + fmt.Sprintf(" AND u.root_id = %v", u.RootId)
	}
	if u.Level != 0 {
		if u.Level >= Level2 {
			where = where + fmt.Sprintf(" AND u.level >= %v", u.Level)
		} else {
			where = where + fmt.Sprintf(" AND u.level = %v", u.Level)
		}
	}

	if u.AgentId != 0 {
		where = where + fmt.Sprintf(" AND u.uid = %v", u.AgentId)
	}
	if u.AgentName != "" {
		where = where + fmt.Sprintf(" AND u.nickname LIKE '%v'", "%"+u.AgentName+"%")
	}

	orderName := " create_time "
	order := GetOrderSort("DESC", op.Order)
	if op.OrderName != "" {
		orderName = "c." + op.OrderName
	}

	sql := fmt.Sprintf(`
		SELECT
			u.*,
			c.card_num,c.amount,c.total_card_num,c.open_fee
		FROM
			%v AS u
		LEFT JOIN
			%v AS c
		ON u.uid = c.uid
		WHERE
			%v
		ORDER BY
			%v %v
		LIMIT ?,?
		`, TablePfUser, TablePfCardCash, where, orderName, order)
	o := NewOrm(multiOrm, DBChessPartner)
	var user []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&user)
	if CheckError(err) {
		return user, 0, err
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS u WHERE %v`, TablePfUser, where)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return user, count, err
	}
	return user, count, nil
}

//----------------------------------合伙人系统的提现相关----------------下面----------------------
//提现记录
func ListPfWithdraw(p ListParams, t ListDayParams, id, uid, status int64, multiOrm ...orm.Ormer) ([]orm.Params, int64, int64, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	where := "1=1"
	if id != 0 {
		where = where + fmt.Sprintf(" AND w.id = %v", id)
	}
	if uid != 0 {
		where = where + fmt.Sprintf(" AND w.agent_id = %v", uid)
	}
	if status != 0 {
		where = where + fmt.Sprintf(" AND w.status = %v", status)
	}
	where2 := " 1=1 "
	if t.StartTime > 0 && t.EndTime > t.StartTime {
		where = where + fmt.Sprintf(" AND w.create_time >= %v AND w.create_time < %v", t.StartTime, t.EndTime)
		where2 = fmt.Sprintf(" AND w.create_time >= %v AND w.create_time < %v", t.StartTime, t.EndTime)
	}

	sql := fmt.Sprintf(`
		SELECT
			w.*,b.name,b.bank_name,b.province,b.city,b.card_num,b.branch
		FROM
			%v AS w
		INNER JOIN
			%v AS u
		ON w.agent_id = u.uid
		LEFT JOIN
			%v AS b
		ON w.agent_id = b.uid
		WHERE
			%v
		ORDER BY
			w.id DESC
		LIMIT ?,?
	`, TablePfWithdrawRecord, TablePfUser, TablePfAgentBank, where)
	o := NewOrm(multiOrm, DBChessPartner)
	var wr []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&wr)
	if CheckError(err) {
		return wr, 0, 0, 0, err
	}
	var count int64
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v AS w INNER JOIN %v AS u ON w.agent_id = u.uid WHERE %v`,
		TablePfWithdrawRecord, TablePfUser, where)
	err = o.Raw(sql).QueryRow(&count)
	if CheckError(err) {
		return wr, 0, 0, 0, err
	}
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(w.amount) is NULL,0,SUM(w.amount)) AS processed_amount
		FROM
			%v AS w
		WHERE
			%v AND w.status = %v
	`, TablePfWithdrawRecord, where2, WithdrawPaySuccess)
	var pAmount, uAmount int64
	o.Raw(sql).QueryRow(&pAmount)
	sql = fmt.Sprintf(`
		SELECT
			IF(SUM(w.amount) is NULL,0,SUM(w.amount)) AS unprocessed_amount
		FROM
			%v AS w
		WHERE
			%v AND w.status < %v
	`, TablePfWithdrawRecord, where2, WithdrawPaySuccess)
	o.Raw(sql).QueryRow(&uAmount)
	return wr, count, pAmount, uAmount, nil
}

//更新提现记录(一般就是状态及失败原因)
func UpdatePfWithdraw(wr map[string]interface{}, id int64, multiOrm ...orm.Ormer) (int64, error) {
	o := NewOrm(multiOrm, DBChessPartner)
	condition := fmt.Sprintf(`id = %v`, id)
	values, sql := UpdateSql(TablePfWithdrawRecord, wr, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

//获取提现信息
func PfWithdrawById(id int64, multiOrm ...orm.Ormer) (*WithdrawRecord, error) {
	sql := fmt.Sprintf(`
		SELECT
			*
		FROM
			%v
		WHERE
			id = %v
	`, TablePfWithdrawRecord, id)
	o := NewOrm(multiOrm, DBChessPartner)
	var wr WithdrawRecord
	err := o.Raw(sql).QueryRow(&wr)
	if CheckNoExist(err) {
		return nil, nil
	}
	return &wr, err
}

//-------------------------------------合伙人系统提现---------------上面--------------------

//--------------------------------财务方面---------------------下面
